package ph.com.gs3.formalistics.services;

import ph.com.gs3.formalistics.model.vo.business.User;
import ph.com.gs3.formalistics.presenter.notification.ServiceEventNotifierUtility;
import ph.com.gs3.formalistics.services.managers.SessionManager;
import ph.com.gs3.formalistics.services.managers.SessionManager.LoginException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

public class AuthenticationService extends IntentService {

	public static final String TAG = AuthenticationService.class.getSimpleName();

	public static final String NAME = AuthenticationService.class.getName();

	public static final String ACTION_ON_LOGIN_FAILED = NAME + "_login_failed";
	public static final String ACTION_ON_LOGIN_SUCCESS = NAME + "_login_success";

	// Incoming extras
	public static final String EXTRA_SERVER = "server";
	public static final String EXTRA_EMAIL = "email";
	public static final String EXTRA_PASSWORD = "password";

	// Outgoing extras
	public static final String EXTRA_LOGIN_FAILED_EXCEPTION = "login_failed_exception";
	public static final String EXTRA_AUTHENTICATED_USER = "authenticated_user";

	public AuthenticationService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		// display notification
		ServiceEventNotifierUtility.getDefaultInstance().displayBasicNotification(this,
		        "Authenticating");

		// initialize parameters
		Bundle extras = intent.getExtras();

		String server = extras.getString(EXTRA_SERVER);
		String email = extras.getString(EXTRA_EMAIL);
		String password = extras.getString(EXTRA_PASSWORD);

		// login
		SessionManager sessionMan = SessionManager.getApplicationInstance();
		try {
			User authenticatedUser = sessionMan.login(server, email, password);
			broadcastLoginSuccess(authenticatedUser);
		} catch (LoginException e) {
			broadcastLoginFailed(e);
		}

		// dismiss notification
		ServiceEventNotifierUtility.getDefaultInstance().dismissPrimaryNotification(this);

	}

	private void broadcastLoginSuccess(User authenticatedUser) {

		Intent broadcastIntent = new Intent();
		broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);

		broadcastIntent.setAction(ACTION_ON_LOGIN_SUCCESS);
		broadcastIntent.putExtra(EXTRA_AUTHENTICATED_USER, authenticatedUser);

		sendBroadcast(broadcastIntent);

		stopSelf();

	}

	private void broadcastLoginFailed(LoginException e) {

		Intent broadcastIntent = new Intent();
		broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);

		broadcastIntent.setAction(ACTION_ON_LOGIN_FAILED);
		broadcastIntent.putExtra(EXTRA_LOGIN_FAILED_EXCEPTION, e);

		sendBroadcast(broadcastIntent);

		stopSelf();

	}

}
